package algorithms.question.class01;

import common.util.MyUtil;

import java.io.File;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 给定一个文件目录的路径，
 * 写一个函数统计这个目录下所有的文件数量并返回
 * 隐藏文件也算，但是文件夹不算
 *
 * @author guichang
 * @date 2021/7/28
 */

@SuppressWarnings("all")
public class Code2_文件数量 {

    public static void main(String[] args) {
        String path = "D:\\Users\\changgui\\Desktop";
        MyUtil.printf("递归：{}", fileCount1(path));
        MyUtil.printf("栈：{}", fileCount2(path));
        MyUtil.printf("队列：{}", fileCount3(path));
    }

    /**
     * 递归
     */
    public static int fileCount1(String path) {
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            return 0;
        }
        if (pathFile.isFile()) {
            return 1;
        }
        if (pathFile.isDirectory()) {
            int ans = 0;
            for (File f : pathFile.listFiles()) {
                if (f.isFile()) {
                    ans++;
                }
                if (f.isDirectory()) {
                    ans += fileCount1(f.getAbsolutePath());
                }
            }
            return ans;
        }
        return 0;
    }

    /**
     * 栈
     */
    public static int fileCount2(String path) {
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            return 0;
        }
        if (pathFile.isFile()) {
            return 1;
        }
        if (pathFile.isDirectory()) {
            int ans = 0;
            Deque<File> stack = new ArrayDeque<>();
            stack.push(pathFile);
            while (!stack.isEmpty()) {
                for(File f : stack.pop().listFiles()) {
                    if (f.isFile()) {
                        ans++;
                    }
                    if (f.isDirectory()) {
                        stack.push(f);
                    }
                }
            }
            return ans;
        }
        return 0;
    }

    /**
     * 队列
     */
    public static int fileCount3(String path) {
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            return 0;
        }
        if (pathFile.isFile()) {
            return 1;
        }
        if (pathFile.isDirectory()) {
            int ans = 0;
            Deque<File> queue = new ArrayDeque<>();
            queue.offer(pathFile);
            while (!queue.isEmpty()) {
                for(File f : queue.poll().listFiles()) {
                    if (f.isFile()) {
                        ans++;
                    }
                    if (f.isDirectory()) {
                        queue.offer(f);
                    }
                }
            }
            return ans;
        }
        return 0;
    }


}